﻿using DataService.Office.WordDTO;
using DataService.Office.WordMain;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;

using DocumentFormat.OpenXml.Wordprocessing;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataService.Office.Word
{
    /// <summary>
    /// 图像长度单位转换
    /// </summary>
    public class ImageExtent
    {
        private const decimal CM_TO_PX = 96M;
        private const decimal INCH_TO_CM = 2.54M;
        /// <summary>
        /// 厘米到EMU（English Metric Unit)
        /// </summary>
        private const decimal CM_TO_EMU = 360000M;

        /// <summary>
        /// EMU（English Metric Unit) 到像素（px）
        /// </summary>
        /// <param name="EMU"></param>
        public static decimal EMU_TO_PX(decimal EMU)
        {
            return EMU / CM_TO_EMU / INCH_TO_CM * CM_TO_PX;
        }
        //1 厘米≈28.35磅
    }
    public class TableRowCellDTO
    {
        public int RowIndex { get; set; }
        public int CellIndex { get; set; }
        public string CellValue { get; set; }
    }

    /// <summary>
    /// 表格
    /// </summary>
    public static class XmlTable
    {
        /// <summary>
        /// 获取body中一个Table
        /// </summary>
        /// <param name="docBody"></param>
        /// <param name="paragraph"></param>
        /// <returns>创建段落后的Table</returns>
        public static Table AfterParagraphTable(Body docBody, OpenXmlElement element)
        {
            return docBody.InsertAfter<Table>(new Table(), element);
        }

        public static Table BeforeParagraphTable(Body docBody, OpenXmlElement element)
        {
            return docBody.InsertBefore<Table>(new Table(), element);
        }


        /// <summary>
        /// 向表格中添加数据（不合并表格）
        /// </summary>
        /// <param name="lstData"></param>
        /// <param name="headerArray">   string[] headerArray = new string[] { "表头1", "表头2", "表头三", "表头4", "表头5", "表头6", "表头7", "表头8", "表头9", "表头10" };</param>
        private static void AddTableData(Table weekTable, List<string[]> lstData, string[] headerArray)
        {
            #region 表格
            //表格由 Table、TableRow、TableCell 三级结构构成。那么，向文档中添加一个 9 行 x 6 列的表格
            // DocumentFormat.OpenXml.Wordprocessing.Table weekTable = parentParagraph.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Table());
            weekTable.AppendChild(ReturnTableProperties());
            //表格宽度由 TableWidth 表示，将 TableWidth 添加到 TableProperties 可设置表格宽度
            //我们希望表格宽度充满整个文档，所以将以百分比设置表格宽度，并设为 100%。
            var tabWidth = new TableWidth { Width = "5000", Type = TableWidthUnitValues.Pct };
            weekTable.AppendChild(tabWidth);
            //先添加表头

            TableRow tabHeaderRow = weekTable.AppendChild(new TableRow());//设置列头行
            foreach (var item in headerArray)
            {
                TableRowProperties tabRowProps = tabHeaderRow.AppendChild(new TableRowProperties(new TableRowHeight { Val = 600, HeightType = HeightRuleValues.Exact }));
                TableCell tabCell = tabHeaderRow.AppendChild(new TableCell());
                Paragraph tabCellPara = tabCell.AppendChild(new Paragraph());
                TableCellProperties tabCellProps = tabCell.AppendChild(new TableCellProperties(new TableCellWidth { Width = "10%", Type = TableWidthUnitValues.Pct }));
                tabCellPara.AppendChild(new Run(new Text(item)));
            }
            //行高由 TableRowHeight 表示，通过将 TableRowHeight 添加到 TableRowProperties 来设置行高
            //上面的代码看着好像很对，但实际用 Word 打开生成的文档会报错。
            //如果要 Word 能够正常打开文档，每个 TableCell 至少需包含一个空段落才行。
            foreach (string[] rowArray in lstData)
            {
                TableRow tabRow = weekTable.AppendChild(new TableRow());
                TableRowProperties tabRowProps = tabRow.AppendChild(new TableRowProperties(new TableRowHeight { Val = 600, HeightType = HeightRuleValues.Exact }));
                //列宽可以通过设置单元格的宽度实现
                foreach (string strCell in rowArray)
                {
                    TableCell tabCell = tabRow.AppendChild(new TableCell());
                    TableCellProperties tabCellProps;
                    tabCellProps = tabCell.AppendChild(new TableCellProperties(new TableCellWidth { Width = "10%", Type = TableWidthUnitValues.Pct }));
                    Paragraph tabCellPara = tabCell.AppendChild(new Paragraph());
                    tabCellPara.AppendChild(new Run(new Text(strCell)));//这里写入单元格的值
                }
                //for (int col = 0; col < headerArray.Length; col++)
                //{
                //    TableCell tabCell = tabRow.AppendChild(new TableCell());
                //    TableCellProperties tabCellProps;
                //    if (col == 0)
                //    {
                //        tabCellProps = tabCell.AppendChild(new TableCellProperties(new TableCellWidth { Width = "10%", Type = TableWidthUnitValues.Pct }));
                //    }
                //    else
                //    {
                //        tabCellProps = tabCell.AppendChild(new TableCellProperties(new TableCellWidth { Width = "10%", Type = TableWidthUnitValues.Pct }));
                //    }
                //    Paragraph tabCellPara = tabCell.AppendChild(new Paragraph());
                //    tabCellPara.AppendChild(new Run(new Text("")));//这里写入单元格的值
                //}
            }
            #endregion

        }

        public static void AddImgTextTable(Table weekTable, List<object[]> lstData, string[] headerArray)
        {
            #region 表格
            //表格由 Table、TableRow、TableCell 三级结构构成。那么，向文档中添加一个 9 行 x 6 列的表格
            //DocumentFormat.OpenXml.Wordprocessing.Table weekTable = parentParagraph.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Table());
            weekTable.AppendChild(ReturnTableProperties());
            //表格宽度由 TableWidth 表示，将 TableWidth 添加到 TableProperties 可设置表格宽度
            //我们希望表格宽度充满整个文档，所以将以百分比设置表格宽度，并设为 100%。
            var tabWidth = new TableWidth { Width = "5000", Type = TableWidthUnitValues.Pct };
            weekTable.AppendChild(tabWidth);

            if (headerArray != null && headerArray.Length > 0)
            {
                TableRow tabHeaderRow = weekTable.AppendChild(new TableRow());//设置列头行
                foreach (var item in headerArray)
                {
                    TableRowProperties tabRowProps = tabHeaderRow.AppendChild(new TableRowProperties(new TableRowHeight { Val = 600, HeightType = HeightRuleValues.Exact }));
                    TableCell tabCell = tabHeaderRow.AppendChild(new TableCell());
                    Paragraph tabCellPara = tabCell.AppendChild(new Paragraph());
                    TableCellProperties tabCellProps = tabCell.AppendChild(new TableCellProperties(new TableCellWidth { Width = "10%", Type = TableWidthUnitValues.Pct }));
                    tabCellPara.AppendChild(new Run(new Text(item)));
                }
            }
            //行高由 TableRowHeight 表示，通过将 TableRowHeight 添加到 TableRowProperties 来设置行高
            //上面的代码看着好像很对，但实际用 Word 打开生成的文档会报错。
            //如果要 Word 能够正常打开文档，每个 TableCell 至少需包含一个空段落才行。
            foreach (object[] rowArray in lstData)
            {
                TableRow tabRow = weekTable.AppendChild(new TableRow());
                TableRowProperties tabRowProps = tabRow.AppendChild(new TableRowProperties(new TableRowHeight { Val = 1500, HeightType = HeightRuleValues.Exact }));
                //列宽可以通过设置单元格的宽度实现
                foreach (object objCellValue in rowArray)
                {
                    TableCell tabCell = tabRow.AppendChild(new TableCell());
                    TableCellProperties tabCellProps;
                    tabCellProps = tabCell.AppendChild(new TableCellProperties(new TableCellWidth { Width = "10%", Type = TableWidthUnitValues.Pct }));
                    if (objCellValue == null || objCellValue == DBNull.Value)
                    {
                        Paragraph tabCellPara = tabCell.AppendChild(new Paragraph());
                        tabCellPara.AppendChild(new Run(new Text("")));//这里写入单元格的值
                    }
                    if (objCellValue != null && objCellValue != DBNull.Value && objCellValue is string)
                    {
                        Paragraph tabCellPara = tabCell.AppendChild(new Paragraph());
                        tabCellPara.AppendChild(new Run(new Text(objCellValue.ToString())));//这里写入单元格的值
                    }
                    if (objCellValue != null && objCellValue is Stream)
                    {
                        string tempRelationId = Guid.NewGuid().ToString().ToUpper();//先暂时使用，如果报错需要使用wordIndex.mainDoc.GetIdOfPart(imagePart)，参考读取body元素
                        XmlToImg.AddImageToTableCell(tabCell, tempRelationId);
                    }

                }
            }
            #endregion

        }


        /// <summary>
        /// 表格，修改表格内容
        /// </summary>
        public static void EditTable(MainDocumentPart mainPart, Table tagertTable, List<WordTableDTO> wordTableDTOArray, WordAppendRowDTO wordAppendDataDTO)
        {
            XmlPackageBussiness xmlPackageBussiness = new XmlPackageBussiness();
            IEnumerable<TableRow> tableRowArray = tagertTable.Elements<TableRow>();

            OpenXmlElement rowElement = null;
            foreach (var tableRow in tableRowArray)
            {
                foreach (var tableCell in tableRow.Elements<TableCell>())
                {
                    string cellVal = tableCell.InnerText;
                    cellVal = cellVal.Replace(" ", "");
                    var wordTableDTO = wordTableDTOArray.Find(x => x.Cell_Key == cellVal);
                    if (wordTableDTO != null && wordTableDTO.TableContentType == (int)WordTableContentEnum.单行单值文字)
                    {
                        ReplaceCellVal(tableCell, wordTableDTO.Cell_Key, wordTableDTO.Cell_Value);
                    }
                    if (wordTableDTO != null && wordTableDTO.TableContentType == (int)WordTableContentEnum.单行多值文字)
                    {
                        ReplaceCellVal(tableCell, wordTableDTO.Cell_Key, wordTableDTO.Cell_Value);
                    }
                    if (wordTableDTO != null && wordTableDTO.TableContentType == (int)WordTableContentEnum.图片)
                    {
                        ReplaceCellVal(tableCell, wordTableDTO.Cell_Key, string.Empty);

                        var cellParagraphs = tableCell.Descendants<Paragraph>();
                        if (cellParagraphs == null || cellParagraphs.Count() == 0)
                        {
                            tableCell.Append(new Paragraph());
                        }
                        Paragraph firstParagraph = cellParagraphs.First();
                        xmlPackageBussiness.AddImageToParagraph(mainPart, tableCell, firstParagraph, wordTableDTO.Cell_Drawings);
                    }
                    if (wordTableDTO != null && wordTableDTO.TableContentType == (int)WordTableContentEnum.多行集合)
                    {
                        rowElement = tableRow;
                        wordAppendDataDTO.Cell_Key = cellVal;
                    }
                }
            }
            if (wordAppendDataDTO != null && wordAppendDataDTO.AppendDataTable != null && wordAppendDataDTO.AppendDataTable.Rows.Count > 0 && rowElement != null)
            {
                FullTableRow(tagertTable, wordAppendDataDTO.AppendDataTable, wordAppendDataDTO.CellsMerge ?? new List<TableMergeCellDTO>(), wordAppendDataDTO.RowsMerge ?? new List<TableVerticalMergeDTO>(), wordAppendDataDTO.TableStyles, rowElement);
            }
        }
        private static void ReplaceCellVal(TableCell tableCell, string oldVal, string newVal)
        {
            var cellRuns = tableCell.Descendants<Run>();
            //if (cellRuns == null)
            //{
            //    tableCell.Descendants<Paragraph>().First().AppendChild<Run>(new Run());
            //}
            int rs_Count = cellRuns.Count();
            if (rs_Count == 1)
            {
                var text = cellRuns.First().Descendants<Text>().First();
                text.Text = text.Text.Replace(oldVal, newVal);
            }
            else if (rs_Count > 1)
            {
                foreach (Run itemRun in cellRuns)
                {
                    var firstTexts = itemRun.Descendants<Text>();
                    foreach (Text itemText in firstTexts)
                    {
                        itemText.Text = string.Empty;
                    }
                }
                var newFirstRunText = cellRuns.First().Descendants<Text>();
                if (newFirstRunText != null && newFirstRunText.Count() > 0)
                {
                    var newFirstText = newFirstRunText.First();
                    newFirstText.Text = newVal;
                }
                else
                {
                    Text text = new Text();
                    text.Text = newVal;
                    cellRuns.First().AppendChild(text);
                }
            }
        }

        private static void RemoveCellContent(TableCell tableCell)
        {
            var cellRuns = tableCell.Descendants<Run>();
            //if (cellRuns == null)
            //{
            //    tableCell.Descendants<Paragraph>().First().AppendChild<Run>(new Run());
            //}
            int rs_Count = cellRuns.Count();
            if (rs_Count == 1)
            {
                var text = cellRuns.First().Descendants<Text>().First();
                text.Text = string.Empty;
            }
            else if (rs_Count > 1)
            {
                foreach (Run itemRun in cellRuns)
                {
                    var firstTexts = itemRun.Descendants<Text>();
                    foreach (Text itemText in firstTexts)
                    {
                        itemText.Text = string.Empty;
                    }
                }
            }
        }
        /// <summary>
        /// /表格写入文本
        /// </summary>
        /// <param name="cellMerge">水平合并单元格参数</param>
        /// <param name="verticalMergeDTO">纵向合并单元格参数</param>
        public static void AddTextTable(Table weekTable, DataTable dataTable, List<TableMergeCellDTO> cellMerge, List<TableVerticalMergeDTO> verticalMergeDTO, List<TableTextStyle> tableTextStyles)
        {
            if (dataTable.Columns.Count == 0)
            {
                return;
            }
            #region 表格
            //表格由 Table、TableRow、TableCell 三级结构构成。那么，向文档中添加一个 9 行 x 6 列的表格
            // DocumentFormat.OpenXml.Wordprocessing.Table weekTable = parentParagraph.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Table());
            weekTable.AppendChild(ReturnTableProperties());
            //表格宽度由 TableWidth 表示，将 TableWidth 添加到 TableProperties 可设置表格宽度
            //我们希望表格宽度充满整个文档，所以将以百分比设置表格宽度，并设为 100%。
            var tabWidth = new TableWidth { Width = "100%", Type = TableWidthUnitValues.Pct };
            weekTable.AppendChild(tabWidth);
            //先添加表头

            TableRow tabHeaderRow = weekTable.AppendChild(new TableRow());//设置列头行
            var headerCellMerges = cellMerge.Where(x => x.RowIndex == 1 && x.CellEndMerge > x.CellStartMerge).ToList();
            int headerMergeCell = 0;
            int tempParamCount = dataTable.Columns.Count;
            int tempWidthRat = 100 / tempParamCount;
            List<string> columnNameList = new List<string>();
            string tableCellWidth = $"{tempWidthRat}%";
            XmlTextStyleDTO tableHeaderTextStyleDTO = new XmlTextStyleDTO
            {
                Algin = Algin.Center,
                FontBold = true
            };
            for (int c = 0; c < dataTable.Columns.Count; c++)
            {
                TableRowProperties tabRowProps = tabHeaderRow.AppendChild(new TableRowProperties(new TableRowHeight { Val = 600, HeightType = HeightRuleValues.Auto }));
                TableCell tabCell = tabHeaderRow.AppendChild(new TableCell());

                var cpr = new TableCellProperties(new TableCellWidth { Width = tableCellWidth, Type = TableWidthUnitValues.Pct });
                if (headerCellMerges.Count() > 0)
                {
                    headerMergeCell = SetHorizontalMerge(headerMergeCell, (c + 1), headerCellMerges, cpr);
                }
                tabCell.Append(cpr);
                Paragraph tabCellPara = tabCell.AppendChild(new Paragraph());
                tabCellPara.AppendChild(new Run(new Text(dataTable.Columns[c].ColumnName)));

                XmlStyle.SetBodyContentStyle(tabCellPara, tableHeaderTextStyleDTO);
                columnNameList.Add(dataTable.Columns[c].ColumnName);
            }
            XmlTextStyleDTO tableContentStyleDTO = new XmlTextStyleDTO
            {
                Algin = Algin.Center
            };
            //行高由 TableRowHeight 表示，通过将 TableRowHeight 添加到 TableRowProperties 来设置行高
            //上面的代码看着好像很对，但实际用 Word 打开生成的文档会报错。
            //如果要 Word 能够正常打开文档，每个 TableCell 至少需包含一个空段落才行。
            Dictionary<int, string> recordDic = new Dictionary<int, string>();
            for (int rowIndex = 0; rowIndex < dataTable.Rows.Count; rowIndex++)
            {
                TableRow tabRow = weekTable.AppendChild(new TableRow());
                TableRowProperties tabRowProps = tabRow.AppendChild(new TableRowProperties(new TableRowHeight { Val = 600, HeightType = HeightRuleValues.Auto }));

                TableTextStyle tempRowStyle = tableTextStyles?.Find(x => x.RowIndex == (rowIndex + 1));
                if (tempRowStyle != null)
                {

                    SetRowStyle(tempRowStyle, tabRowProps);
                }
                //列宽可以通过设置单元格的宽度实现
                int startMergeCell = 0;
                for (int i = 0; i < columnNameList.Count; i++)
                {
                    TableCell tabCell = tabRow.AppendChild(new TableCell());
                    TableCellProperties tabCellProps = new TableCellProperties(new TableCellWidth { Width = tableCellWidth, Type = TableWidthUnitValues.Pct });
                    //横向合并
                    int tempIndex = rowIndex + 2;//第几行合并列，行数=当前行数+表头行数，当前行数=数据行索引+1，因为第1行是表头
                    var rowCellMerges = cellMerge.Where(x => x.RowIndex == tempIndex && x.CellEndMerge > x.CellStartMerge).ToList();
                    if (rowCellMerges.Count() > 0)
                    {
                        startMergeCell = SetHorizontalMerge(startMergeCell, (i + 1), rowCellMerges, tabCellProps);
                    }
                    //纵向合并
                    if (verticalMergeDTO.Any(x => x.ColumnIndex == (i + 1)))
                    {
                        string tempValue = dataTable.Rows[rowIndex][i]?.ToString();
                        if (!string.IsNullOrEmpty(tempValue))
                        {
                            SetVerticalMerge((i + 1), tempValue, recordDic, tabCellProps);
                            recordDic[(i + 1)] = tempValue;
                        }
                    }
                    tabCell.Append(tabCellProps);
                    Paragraph tabCellPara = tabCell.AppendChild(new Paragraph());
                    if (tempRowStyle != null)
                    {
                        SetCellStyle(tempRowStyle, tabCellPara, tabCellProps);
                    }
                    string val = dataTable.Rows[rowIndex][i] == null ? "" : dataTable.Rows[rowIndex][i].ToString();
                    tabCellPara.AppendChild(new Run(new Text(val)));//这里写入单元格的值

                    XmlStyle.SetBodyContentStyle(tabCellPara, tableContentStyleDTO);
                }
            }
            #endregion

        }
        private static void FullTableRow(Table weekTable, DataTable dataTable, List<TableMergeCellDTO> cellMerge, List<TableVerticalMergeDTO> verticalMergeDTO, List<TableTextStyle> tableTextStyles, OpenXmlElement sourceRowXml)
        {
            Dictionary<int, string> recordDic = new Dictionary<int, string>();
            List<string> columnNameList = new List<string>();
            int tempParamCount = dataTable.Columns.Count;
            int tempWidthRat = 100 / tempParamCount;
            string tableCellWidth = $"{tempWidthRat}%";

            for (int c = 0; c < dataTable.Columns.Count; c++)
            {
                columnNameList.Add(dataTable.Columns[c].ColumnName);
            }
            XmlTextStyleDTO tableContentStyleDTO = new XmlTextStyleDTO
            {
                Algin = Algin.Center
            };
            OpenXmlElement firstElement = sourceRowXml;//第一个元素，需要删除
            for (int rowIndex = 0; rowIndex < dataTable.Rows.Count; rowIndex++)
            {
                var appendRowXml = sourceRowXml.CloneNode(true);
                TableRow newTableRow = appendRowXml as TableRow;
                OpenXmlElement tabRow = sourceRowXml as TableRow;
                tabRow = weekTable.InsertAfter<TableRow>(newTableRow, tabRow);
                if (firstElement != null)
                {
                    firstElement.Remove();
                    firstElement = null;
                }
                sourceRowXml = tabRow;
                TableRowProperties tabRowProps = null;
                var tableRowPropertiesArray = tabRow.Descendants<TableRowProperties>();
                if (tableRowPropertiesArray != null)
                {
                    tabRowProps = tableRowPropertiesArray.First();
                }
                else
                {
                    tabRowProps = tabRow.AppendChild(new TableRowProperties());
                }
                TableTextStyle tempRowStyle = tableTextStyles?.Find(x => x.RowIndex == (rowIndex + 1));
                if (tempRowStyle != null)
                {

                    SetRowStyle(tempRowStyle, tabRowProps);
                }
                //列宽可以通过设置单元格的宽度实现
                int startMergeCell = 0;
                var tableCellArrays = tabRow.Descendants<TableCell>();
                int tempCellIndex = -1;
                foreach (TableCell itemTableCell in tableCellArrays)
                {
                    tempCellIndex++;
                    RemoveCellContent(itemTableCell);
                    TableCellProperties tabCellProps = null;
                    var tabCellPropsArray = itemTableCell.Descendants<TableCellProperties>();
                    if (tabCellPropsArray != null)
                    {
                        tabCellProps = tabCellPropsArray.First();
                    }
                    else
                    {
                        tabCellProps = new TableCellProperties();
                        itemTableCell.Append(tabCellProps);
                    }
                    // TableCellProperties tabCellProps = new TableCellProperties(new TableCellWidth { Width = tableCellWidth, Type = TableWidthUnitValues.Pct });
                    //横向合并
                    int tempIndex = rowIndex + 2;//第几行合并列，行数=当前行数+表头行数，当前行数=数据行索引+1，因为第1行是表头
                    var rowCellMerges = cellMerge.Where(x => x.RowIndex == tempIndex && x.CellEndMerge > x.CellStartMerge).ToList();
                    if (rowCellMerges.Count() > 0)
                    {
                        startMergeCell = SetHorizontalMerge(startMergeCell, (tempCellIndex + 1), rowCellMerges, tabCellProps);
                    }
                    //纵向合并
                    if (verticalMergeDTO.Any(x => x.ColumnIndex == (tempCellIndex + 1)))
                    {
                        string tempValue = dataTable.Rows[rowIndex][tempCellIndex]?.ToString();
                        if (!string.IsNullOrEmpty(tempValue))
                        {
                            SetVerticalMerge((tempCellIndex + 1), tempValue, recordDic, tabCellProps);
                            recordDic[(tempCellIndex + 1)] = tempValue;
                        }
                    }
                    Paragraph tabCellPara = null;
                    var tableCellParagraphArray = itemTableCell.Descendants<Paragraph>();
                    if (tableCellParagraphArray != null)
                    {
                        tabCellPara = tableCellParagraphArray.First();
                    }
                    else
                    {
                        tabCellPara = itemTableCell.AppendChild(new Paragraph());
                    }
                    if (tempRowStyle != null)
                    {
                        SetCellStyle(tempRowStyle, tabCellPara, tabCellProps);
                    }
                    string val = dataTable.Rows[rowIndex][tempCellIndex] == null ? "" : dataTable.Rows[rowIndex][tempCellIndex].ToString();

                    var textArray = tabCellPara.Descendants<Text>();
                    if (textArray != null)
                    {
                        Text cellText = textArray.First();
                        cellText.Text = val;
                    }
                    else
                    {
                        tabCellPara.AppendChild(new Run(new Text(val)));//这里写入单元格的值
                    }
                    XmlStyle.SetBodyContentStyle(tabCellPara, tableContentStyleDTO);
                }
            }
        }
        private static void SetRowStyle(TableTextStyle tableTextStyle, TableRowProperties tableRowProperties)
        {
            if (!string.IsNullOrWhiteSpace(tableTextStyle.BackColorName))
            {
                //            var hx16Color = XmlPackageColor.ColorNametoHx16(tableTextStyle.BackColorName);
                //            DocumentFormat.OpenXml.Wordprocessing.Shading shading =
                //new DocumentFormat.OpenXml.Wordprocessing.Shading()
                //{
                //    Color = "auto",
                //    Fill = hx16Color,
                //    Val = ShadingPatternValues.Clear
                //};
                //            tableRowProperties.AppendChild(shading);

            }
            if (tableTextStyle.FontSizeEnum > 0)
            {
                float tempBangZhi = XmlStyle.GetWordBang(tableTextStyle.FontSizeEnum);
                FontSize fontSize = new FontSize();

                fontSize.Val = (tempBangZhi * 2).ToString();
                tableRowProperties.AppendChild(fontSize);
            }
            if (tableTextStyle.FontFamilysEnum > 0)
            {
                RunFonts runFonts = runFonts = new RunFonts();
                string fontName = tableTextStyle.FontFamilysEnum.ToString();
                runFonts.Ascii = fontName;
                runFonts.HighAnsi = fontName;
                runFonts.EastAsia = fontName;
                tableRowProperties.AppendChild(runFonts);
            }
        }
        private static void SetCellStyle(TableTextStyle tableTextStyle, Paragraph paragraph, TableCellProperties tabCellProps)
        {
            if (!string.IsNullOrWhiteSpace(tableTextStyle.ColorName))
            {
                XmlTextStyleDTO xmlTextStyleDTO = new XmlTextStyleDTO();
                xmlTextStyleDTO.ColorName = tableTextStyle.ColorName;
                XmlStyle.SetBodyContentStyle(paragraph, xmlTextStyleDTO);
            }
            if (!string.IsNullOrWhiteSpace(tableTextStyle.BackColorName))
            {
                var hx16Color = XmlPackageColor.ColorNametoHx16(tableTextStyle.BackColorName);
                DocumentFormat.OpenXml.Wordprocessing.Shading shading =
    new DocumentFormat.OpenXml.Wordprocessing.Shading()
    {
        Color = "auto",
        Fill = hx16Color,
        Val = ShadingPatternValues.Clear
    };
                tabCellProps.AppendChild(shading);

            }
        }
        /// <summary>
        /// 水平合并
        /// </summary>
        private static int SetHorizontalMerge(int startMergeCell, int columnIndex, List<TableMergeCellDTO> cellMerge, TableCellProperties cellRpr)
        {
            //水平合并：HorizontalMerge
            //纵向合并：VerticalMerge
            int temValue = startMergeCell;
            if (startMergeCell == 0)
            {
                //寻找合并的开始位置
                var tempCellDTO = cellMerge.Find(x => x.CellStartMerge == columnIndex);
                if (tempCellDTO != null)
                {
                    HorizontalMerge horizontalMerge = new HorizontalMerge()
                    {
                        Val = MergedCellValues.Restart
                    };
                    cellRpr.AppendChild(horizontalMerge);
                    temValue = columnIndex;
                }
            }
            if (startMergeCell > 0)
            {
                //寻找合并的结束位置
                var tempCellDTO = cellMerge.Find(x => x.CellStartMerge == startMergeCell && x.CellEndMerge == columnIndex);
                if (tempCellDTO != null)
                {
                    HorizontalMerge horizontalMerge = new HorizontalMerge()
                    {
                        Val = MergedCellValues.Continue
                    };
                    cellRpr.AppendChild(horizontalMerge);
                    temValue = 0;
                }
            }
            return temValue;
        }

        /// <summary>
        /// 纵向合并
        /// </summary>
        /// <returns></returns>
        private static void SetVerticalMerge(int currColIndex, string currCellVal, Dictionary<int, string> dic, TableCellProperties cellRpr)
        {
            VerticalMerge verticalMerge = new VerticalMerge();
            if (dic.ContainsKey(currColIndex))
            {
                string tempValue = dic[currColIndex];
                if (tempValue == currCellVal)
                {
                    verticalMerge.Val = MergedCellValues.Continue;
                }
                else
                {
                    verticalMerge.Val = MergedCellValues.Restart;
                }
            }
            else
            {
                verticalMerge.Val = MergedCellValues.Restart;
            }
            cellRpr.AppendChild(verticalMerge);
        }
        /// <summary>
        /// 设置纵向合并
        /// </summary>
        public static void SetVerticalMerge(DocumentFormat.OpenXml.Wordprocessing.TableCell wordTableCell, MergedCellValues mergedCellValues)
        {
            VerticalMerge verticalMerge = new VerticalMerge();
            verticalMerge.Val = mergedCellValues;
            TableCellProperties tableCellPro = wordTableCell.TableCellProperties;
            if (tableCellPro == null)
            {
                tableCellPro = new TableCellProperties();
                tableCellPro.AppendChild(verticalMerge);

                wordTableCell.AppendChild(tableCellPro);
            }
            else
            {
                tableCellPro.AppendChild(verticalMerge);
                // wordTableCell.Append(tableCellPro);
            }

        }
        /// <summary>
        /// 设置横向向合并
        /// </summary>
        public static void SetHorizontalMerge(DocumentFormat.OpenXml.Wordprocessing.TableCell wordTableCell, MergedCellValues mergedCellValues)
        {
            HorizontalMerge horizontalMerge = new HorizontalMerge();
            horizontalMerge.Val = mergedCellValues;
            TableCellProperties tableCellPro = wordTableCell.TableCellProperties;
            if (tableCellPro == null)
            {
                tableCellPro = new TableCellProperties();
                tableCellPro.AppendChild(horizontalMerge);

                wordTableCell.AppendChild(tableCellPro);
            }
            else
            {
                tableCellPro.AppendChild(horizontalMerge);
                // wordTableCell.Append(tableCellPro);
            }

        }

        /// <summary>
        /// 添加表格
        /// </summary>
        /// <param name="lstData"></param>
        /// <param name="headerArray">   string[] headerArray = new string[] { "表头1", "表头2", "表头三", "表头4", "表头5", "表头6", "表头7", "表头8", "表头9", "表头10" };</param>
        public static void AddTable(DocumentFormat.OpenXml.Wordprocessing.Body docBody, List<string[]> lstData, string[] headerArray)
        {
            #region 表格
            //表格由 Table、TableRow、TableCell 三级结构构成。那么，向文档中添加一个 9 行 x 6 列的表格
            DocumentFormat.OpenXml.Wordprocessing.Table weekTable = docBody.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Table());
            weekTable.AppendChild(ReturnTableProperties());
            //表格宽度由 TableWidth 表示，将 TableWidth 添加到 TableProperties 可设置表格宽度
            //我们希望表格宽度充满整个文档，所以将以百分比设置表格宽度，并设为 100%。
            var tabWidth = new TableWidth { Width = "5000", Type = TableWidthUnitValues.Pct };
            weekTable.AppendChild(tabWidth);
            //先添加表头

            TableRow tabHeaderRow = weekTable.AppendChild(new TableRow());//设置列头行
            foreach (var item in headerArray)
            {
                TableRowProperties tabRowProps = tabHeaderRow.AppendChild(new TableRowProperties(new TableRowHeight { Val = 600, HeightType = HeightRuleValues.Exact }));
                TableCell tabCell = tabHeaderRow.AppendChild(new TableCell());
                Paragraph tabCellPara = tabCell.AppendChild(new Paragraph());
                TableCellProperties tabCellProps = tabCell.AppendChild(new TableCellProperties(new TableCellWidth { Width = "10%", Type = TableWidthUnitValues.Pct }));
                tabCellPara.AppendChild(new Run(new Text(item)));
            }
            //行高由 TableRowHeight 表示，通过将 TableRowHeight 添加到 TableRowProperties 来设置行高
            //上面的代码看着好像很对，但实际用 Word 打开生成的文档会报错。
            //如果要 Word 能够正常打开文档，每个 TableCell 至少需包含一个空段落才行。
            foreach (string[] rowArray in lstData)
            {
                TableRow tabRow = weekTable.AppendChild(new TableRow());
                TableRowProperties tabRowProps = tabRow.AppendChild(new TableRowProperties(new TableRowHeight { Val = 600, HeightType = HeightRuleValues.Exact }));
                //列宽可以通过设置单元格的宽度实现
                foreach (string strCell in rowArray)
                {
                    TableCell tabCell = tabRow.AppendChild(new TableCell());
                    TableCellProperties tabCellProps;
                    tabCellProps = tabCell.AppendChild(new TableCellProperties(new TableCellWidth { Width = "10%", Type = TableWidthUnitValues.Pct }));
                    Paragraph tabCellPara = tabCell.AppendChild(new Paragraph());
                    tabCellPara.AppendChild(new Run(new Text(strCell)));//这里写入单元格的值
                }
                //for (int col = 0; col < headerArray.Length; col++)
                //{
                //    TableCell tabCell = tabRow.AppendChild(new TableCell());
                //    TableCellProperties tabCellProps;
                //    if (col == 0)
                //    {
                //        tabCellProps = tabCell.AppendChild(new TableCellProperties(new TableCellWidth { Width = "10%", Type = TableWidthUnitValues.Pct }));
                //    }
                //    else
                //    {
                //        tabCellProps = tabCell.AppendChild(new TableCellProperties(new TableCellWidth { Width = "10%", Type = TableWidthUnitValues.Pct }));
                //    }
                //    Paragraph tabCellPara = tabCell.AppendChild(new Paragraph());
                //    tabCellPara.AppendChild(new Run(new Text("")));//这里写入单元格的值
                //}
            }
            #endregion

        }




        /// <summary>
        /// 添加表格（表格内容可以是图片和文字）
        /// </summary>
        /// <param name="lstData">数据行和表头行</param>
        public static void AddImgTextTable(DocumentFormat.OpenXml.Wordprocessing.Body docBody, List<object[]> lstData, string[] headerArray)
        {
            #region 表格
            //表格由 Table、TableRow、TableCell 三级结构构成。那么，向文档中添加一个 9 行 x 6 列的表格
            DocumentFormat.OpenXml.Wordprocessing.Table weekTable = docBody.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Table());
            weekTable.AppendChild(ReturnTableProperties());
            //表格宽度由 TableWidth 表示，将 TableWidth 添加到 TableProperties 可设置表格宽度
            //我们希望表格宽度充满整个文档，所以将以百分比设置表格宽度，并设为 100%。
            var tabWidth = new TableWidth { Width = "5000", Type = TableWidthUnitValues.Pct };
            weekTable.AppendChild(tabWidth);

            if (headerArray != null && headerArray.Length > 0)
            {
                TableRow tabHeaderRow = weekTable.AppendChild(new TableRow());//设置列头行
                foreach (var item in headerArray)
                {
                    TableRowProperties tabRowProps = tabHeaderRow.AppendChild(new TableRowProperties(new TableRowHeight { Val = 600, HeightType = HeightRuleValues.Exact }));
                    TableCell tabCell = tabHeaderRow.AppendChild(new TableCell());
                    Paragraph tabCellPara = tabCell.AppendChild(new Paragraph());
                    TableCellProperties tabCellProps = tabCell.AppendChild(new TableCellProperties(new TableCellWidth { Width = "10%", Type = TableWidthUnitValues.Pct }));
                    tabCellPara.AppendChild(new Run(new Text(item)));
                }
            }
            //行高由 TableRowHeight 表示，通过将 TableRowHeight 添加到 TableRowProperties 来设置行高
            //上面的代码看着好像很对，但实际用 Word 打开生成的文档会报错。
            //如果要 Word 能够正常打开文档，每个 TableCell 至少需包含一个空段落才行。
            foreach (object[] rowArray in lstData)
            {
                TableRow tabRow = weekTable.AppendChild(new TableRow());
                TableRowProperties tabRowProps = tabRow.AppendChild(new TableRowProperties(new TableRowHeight { Val = 1500, HeightType = HeightRuleValues.Exact }));
                //列宽可以通过设置单元格的宽度实现
                foreach (object objCellValue in rowArray)
                {
                    TableCell tabCell = tabRow.AppendChild(new TableCell());
                    TableCellProperties tabCellProps;
                    tabCellProps = tabCell.AppendChild(new TableCellProperties(new TableCellWidth { Width = "10%", Type = TableWidthUnitValues.Pct }));
                    if (objCellValue == null || objCellValue == DBNull.Value)
                    {
                        Paragraph tabCellPara = tabCell.AppendChild(new Paragraph());
                        tabCellPara.AppendChild(new Run(new Text("")));//这里写入单元格的值
                    }
                    if (objCellValue != null && objCellValue != DBNull.Value && objCellValue is string)
                    {
                        Paragraph tabCellPara = tabCell.AppendChild(new Paragraph());
                        tabCellPara.AppendChild(new Run(new Text(objCellValue.ToString())));//这里写入单元格的值
                    }
                    if (objCellValue != null && objCellValue is Stream)
                    {
                        string tempRelationId = Guid.NewGuid().ToString().ToUpper();//先暂时使用，如果报错需要使用wordIndex.mainDoc.GetIdOfPart(imagePart)，参考读取body元素
                        XmlToImg.AddImageToTableCell(tabCell, tempRelationId);
                    }

                }
            }
            #endregion

        }
        /// <summary>
        /// 表格样式
        /// </summary>
        /// <param name="borderColor">边框颜色（十六进制）</param>
        /// <param name="size">线条宽度</param>
        /// <returns></returns>
        public static TableProperties ReturnTableProperties(string borderColor = "4F81BD", uint size = 4U)
        {
            TableProperties tabProps = new TableProperties(new TableBorders(
     new TopBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Color = borderColor },
     new BottomBorder
     {
         Val = new EnumValue<BorderValues>(BorderValues.Single),
         Size = size,
         Color = borderColor
     },
     new LeftBorder
     {
         Val = new EnumValue<BorderValues>(BorderValues.Single),
         Size = size,
         Color = borderColor
     },
     new RightBorder
     {
         Val = new EnumValue<BorderValues>(BorderValues.Single),
         Size = size,
         Color = borderColor
     },
     new InsideHorizontalBorder
     {
         Val = new EnumValue<BorderValues>(BorderValues.Single),
         Size = size,
         Color = borderColor
     },
     new InsideVerticalBorder
     {
         Val = new EnumValue<BorderValues>(BorderValues.Single),
         Size = size,
         Color = borderColor
     }
     ));
            #region 宽度自适应
            var tableWidth = new TableWidth() { Width = "110%", Type = TableWidthUnitValues.Pct };
            tabProps.TableWidth = tableWidth;
            var tableLayout = new TableLayout() { Type = TableLayoutValues.Fixed };
            tabProps.TableLayout = tableLayout;
            #endregion
            #region 宽度设置也可以，需要具体值
            // tabProps.AppendChild(new TableWidth { Width = "16074", Type = TableWidthUnitValues.Dxa });
             tabProps.Append(new TableIndentation {  Width = 0, Type = TableWidthUnitValues.Dxa });
            #endregion

            //对齐方式
            var justification1 = new DocumentFormat.OpenXml.Wordprocessing.Justification { Val = JustificationValues.Center };
            tabProps.Append(justification1);


            //var ddd = new TableCellMargin(new TopMargin { Width = "0" }, new LeftMargin { Width = "10" },new BottomMargin { Width="0"} ,new RightMargin { Width="10"});
            // tabProps.Append(ddd);


            tabProps.Append();



            return tabProps;
        }

        public static void SetTableCellProperties(TableCellProperties tableCellProperties, string borderColor = "4F81BD", uint size = 4U)
        {
            var tableCellBorders = new TableCellBorders(
        new TopBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 1, Color = borderColor },
        new BottomBorder
        {
            Val = new EnumValue<BorderValues>(BorderValues.Single),
            Size = size,
            Color = borderColor
        },
        new LeftBorder
        {
            Val = new EnumValue<BorderValues>(BorderValues.Single),
            Size = size,
            Color = borderColor
        },
        new RightBorder
        {
            Val = new EnumValue<BorderValues>(BorderValues.Single),
            Size = size,
            Color = borderColor
        },
        new InsideHorizontalBorder
        {
            Val = new EnumValue<BorderValues>(BorderValues.Single),
            Size = size,
            Color = borderColor
        },
        new InsideVerticalBorder
        {
            Val = new EnumValue<BorderValues>(BorderValues.Single),
            Size = size,
            Color = borderColor
        }
        );
            var borders = tableCellProperties.TableCellBorders;
            if (borders == null)
            {
                tableCellProperties.AppendChild(tableCellBorders);
            }
            else
            {
                tableCellProperties.TableCellBorders = tableCellBorders;
            }
        }


        /// <summary>
        /// 返回表格中的数据【此方方法适用于表格内全是文字】
        /// </summary>
        /// <param name="openXmlElement">源文件中body的table元素</param>
        /// <returns></returns>
        public static Dictionary<string, object> ReturnTableTextData(OpenXmlElement openXmlElement)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            int isColumnRowIndex = 0;
            List<string> headerList = new List<string>();
            List<string[]> lstData = new List<string[]>();
            int columnCount = 0;
            //1.取出表头(默认只取第一行)
            IEnumerable<TableRow> tableRowArray = openXmlElement.Elements<TableRow>();
            foreach (var tableRow in tableRowArray)
            {
                if (isColumnRowIndex == 0)
                {
                    foreach (var tableCell in tableRow.Elements<TableCell>())
                    {
                        headerList.Add(tableCell.InnerText);
                    }
                    columnCount = headerList.Count;
                }
                else
                {
                    string[] tempArray = new string[columnCount];
                    int tempValue = 0;
                    foreach (var tableCell in tableRow.Elements<TableCell>())
                    {
                        tempArray[tempValue] = tableCell.InnerText;
                        tempValue++;
                    }
                    lstData.Add(tempArray);
                }

                isColumnRowIndex++;
            }
            dic["Header"] = headerList.ToArray();
            dic["RowData"] = lstData;
            return dic;
        }


        public static List<TableRowCellDTO> ReturnTableTableRowCellDTO(OpenXmlElement openXmlElement)
        {
            List<TableRowCellDTO> tableRowCellDTOList = new List<TableRowCellDTO>();
            IEnumerable<TableRow> tableRowArray = openXmlElement.Elements<TableRow>();
            int rowIndex = 0;
            foreach (var tableRow in tableRowArray)
            {
                rowIndex++;
                int cellIndex = 0;
                foreach (var tableCell in tableRow.Elements<TableCell>())
                {
                    cellIndex++;
                    TableRowCellDTO tableRowCellDTO = new TableRowCellDTO
                    {
                        RowIndex = rowIndex,
                        CellIndex = cellIndex,
                        CellValue = tableCell.InnerText
                    };
                    tableRowCellDTOList.Add(tableRowCellDTO);
                }
            }
            return tableRowCellDTOList;
        }

        /// <summary>
        /// 返回表格中的数据【此方方法适用于表格内是文字和图片】
        /// </summary>
        /// <param name="openXmlElement">源文件中body的table元素</param>
        /// <returns></returns>
        public static List<object[]> ReturnTableTextAndImgData(OpenXmlElement xmlElement, DocumentFormat.OpenXml.Packaging.MainDocumentPart mainPart)
        {
            List<object[]> lstData = new List<object[]>();
            IEnumerable<TableRow> tableRowArray = xmlElement.Elements<TableRow>();
            int tempIndex = 0;
            foreach (var tableRow in tableRowArray)
            {
                #region 读取表格内的文字和图片
                List<Object> rowDatas = new List<Object>();
                foreach (var tableCell in tableRow.Elements<TableCell>())
                {
                    object tableCellValue = string.Empty;
                    //这里默认一个单元格内要么是文字要么是图片,如果单元格内既有文字又有图片可以使用tempXmlElement.ChildElements遍历单元格元素,参考遍历body元素
                    var tempXmlElementList = tableCell.Elements();
                    foreach (var tempXmlElement in tempXmlElementList)
                    {
                        if (tempXmlElement is Paragraph)
                        {
                            foreach (var run in tempXmlElement.ChildElements)
                            {
                                if (run is Run)
                                {
                                    foreach (OpenXmlElement runChildElment in run.Elements())
                                    {
                                        if (runChildElment is Text)
                                        {
                                            tableCellValue = runChildElment.InnerText;
                                        }
                                        //图像块
                                        else if (runChildElment is Drawing)
                                        {
                                            long width = 9990L;//图片默认宽,  图片实际宽度(cm)=9990L/360000
                                            long height = 7990L;//图片默认高，图片实际高度(cm)=7990L/360000
                                            Stream stream = XmlToImg.GetStreamByopenXmlElementDrawing(runChildElment, mainPart, ref width, ref height);
                                            tableCellValue = stream;
                                            //  byte[] bytes = new byte[stream.Length];
                                            // stream.Read(bytes, 0, bytes.Length);
                                            //string imgHtml = $"<img style='width:{ImageExtent.EMU_TO_PX((decimal)width).ToString("0.")}px;height:{ImageExtent.EMU_TO_PX((decimal)height).ToString("0.")}px' src='data:{part.ContentType};base64," + Convert.ToBase64String(bytes) + "' />";
                                            // tableCellValue = Convert.ToBase64String(bytes);
                                        }
                                    }

                                }
                            }
                        }
                    }
                    if (tableCellValue != null)
                    {
                        rowDatas.Add(tableCellValue);
                    }

                }
                #endregion

                lstData.Add(rowDatas.ToArray());
                tempIndex++;
            }
            return lstData;
        }


        /// <summary>
        /// 返回表格中的数据【此方方法适用于表格内是文字和图片】
        /// </summary>
        /// <param name="openXmlElement">源文件中body的table元素</param>
        /// <returns></returns>
        public static List<string> ReturnRelationShipIdList(OpenXmlElement xmlElement, DocumentFormat.OpenXml.Packaging.MainDocumentPart mainPart)
        {
            List<string> table_ImgRelationShipIdList = new List<string>();
            IEnumerable<TableRow> tableRowArray = xmlElement.Elements<TableRow>();
            foreach (var tableRow in tableRowArray)
            {
                #region 遍历表格查找表格中的图片的RelationShipId
                foreach (var tableCell in tableRow.Elements<TableCell>())
                {
                    //这里默认一个单元格内要么是文字要么是图片,如果单元格内既有文字又有图片可以使用tempXmlElement.ChildElements遍历单元格元素,参考遍历body元素
                    var tempXmlElementList = tableCell.Elements();
                    foreach (var tempXmlElement in tempXmlElementList)
                    {
                        if (tempXmlElement is Paragraph)
                        {
                            List<string> tempRelationShipIdList = XmlToImg.GetRelationShipIdListByopenXmlElement(tempXmlElement, mainPart);
                            if (tempRelationShipIdList.Count > 0)
                            {
                                table_ImgRelationShipIdList.AddRange(tempRelationShipIdList);
                            }
                            //foreach (var run in tempXmlElement.ChildElements)
                            //{
                            //    if (run is Run)
                            //    {
                            //        foreach (OpenXmlElement runChildElment in run.Elements())
                            //        {
                            //            //图像块
                            //            //if (runChildElment is Drawing)
                            //            //{
                            //            //    string tempRelationShipId = WordImg.GetRelationShipIdByopenXmlElementDrawing(runChildElment, mainPart);
                            //            //    if (!string.IsNullOrEmpty(tempRelationShipId))
                            //            //    {
                            //            //        table_ImgRelationShipIdList.Add(tempRelationShipId);
                            //            //    }

                            //            //}
                            //        }
                            //    }
                            //}
                        }
                    }
                }
                #endregion
            }
            return table_ImgRelationShipIdList;
        }


        public static DataTable ReadWord(OpenXmlElement xmlElement, DocumentFormat.OpenXml.Packaging.MainDocumentPart mainPart)
        {
            DataTable dt = new DataTable();
            int isColumnRowIndex = 0;
            IEnumerable<TableRow> tableRowArray = xmlElement.Elements<TableRow>();
            foreach (var tableRow in tableRowArray)
            {
                if (isColumnRowIndex == 0)
                {
                    foreach (var tableCell in tableRow.Elements<TableCell>())
                    {
                        dt.Columns.Add(tableCell.InnerText);
                    }
                }
                else
                {
                    #region 读取表格内的文字和图片
                    List<Object> rowDatas = new List<Object>();
                    foreach (var tableCell in tableRow.Elements<TableCell>())
                    {
                        object tableCellValue = null;
                        //这里默认一个单元格内要么是文字要么是图片,如果单元格内既有文字又有图片可以使用tempXmlElement.ChildElements遍历单元格元素,参考遍历body元素
                        var tempXmlElement = tableCell.FirstChild;
                        if (tempXmlElement is Paragraph)
                        {
                            foreach (var run in tempXmlElement.ChildElements)
                            {
                                if (run is Run)
                                {
                                    foreach (OpenXmlElement runChildElment in run.Elements())
                                    {
                                        if (runChildElment is Text)
                                        {
                                            tableCellValue = runChildElment.InnerText;
                                        }
                                        //图像块
                                        else if (runChildElment is Drawing)
                                        {
                                            long width = 9990L;//图片默认宽
                                            long height = 7990L;//图片默认高
                                            Stream stream = XmlToImg.GetStreamByopenXmlElementDrawing(runChildElment, mainPart, ref width, ref height);
                                            if (stream != null)
                                            {
                                                byte[] bytes = new byte[stream.Length];
                                                stream.Read(bytes, 0, bytes.Length);
                                                //string imgHtml = $"<img style='width:{ImageExtent.EMU_TO_PX((decimal)width).ToString("0.")}px;height:{ImageExtent.EMU_TO_PX((decimal)height).ToString("0.")}px' src='data:{part.ContentType};base64," + Convert.ToBase64String(bytes) + "' />";
                                                tableCellValue = Convert.ToBase64String(bytes);
                                            }

                                        }
                                    }

                                }
                            }
                        }
                        if (tableCellValue != null)
                        {
                            rowDatas.Add(tableCellValue);
                        }

                    }
                    #endregion
                    dt.Rows.Add(rowDatas.ToArray());
                }
                isColumnRowIndex++;
            }
            return dt;
        }

        /// <summary>
        /// 解决 跨页断行问题
        /// </summary>
        public static void RowCantSplit(ref TableRow tableRow)
        {
            var tableRowProperties = tableRow.TableRowProperties;
            if (tableRowProperties == null)
            {
                tableRowProperties = new TableRowProperties();
            }

            tableRowProperties.Append(new GridAfter { Val = 1 });
            //true，去掉跨页断行对勾（表格行右键， 表格属性-》行->允许跨页断行）
            CantSplit cantSplit = new CantSplit() { Val = OnOffOnlyValues.On };
            tableRowProperties.Append(cantSplit);

            var rowJustification = new DocumentFormat.OpenXml.Wordprocessing.Justification { Val = JustificationValues.Center };
            tableRowProperties.Append(rowJustification);

            //tableRowProperties.Append(new GridBefore { Val = 1 });
            //tableRow.Append(tableRowProperties);

            tableRow.Append(tableRowProperties);

        }


        public static void RowAppendCell(TableRow wordTableRow, string tableCellWidth)
        {
            DocumentFormat.OpenXml.Wordprocessing.TableCell wordTableCell = wordTableRow.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            TableCellProperties tabCellProps = new TableCellProperties(new TableCellWidth { Width = tableCellWidth, Type = TableWidthUnitValues.Pct });

            var tcpr = wordTableCell.AppendChild(tabCellProps);
            Paragraph tabCellPara = wordTableCell.AppendChild(new Paragraph());
            var wordCellRun = new DocumentFormat.OpenXml.Wordprocessing.Run();
            wordCellRun.Append(new DocumentFormat.OpenXml.Wordprocessing.Text(""));
            tabCellPara.Append(wordCellRun);
        }

        //public static void AddTable(DocumentFormat.OpenXml.Wordprocessing.Body docBody, List<string[]> lstData, string[] headerArray)
        //{
        //    TableGrid grid = new TableGrid();
        //    int maxColumnNum = lstData.Select(x => x.Count()).Max();
        //    for (int index = 0; index < maxColumnNum; index++)
        //    {
        //        grid.Append(new TableGrid());
        //    }

        //    // 设置表格边框
        //    TableProperties tblProp = new TableProperties(
        //    new TableBorders(
        //    new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 2 },
        //    new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 2 },
        //    new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 2 },
        //    new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 2 },
        //    new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 2 },
        //    new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 2 }
        //    )
        //    );

        //    Table table = new Table();
        //    table.Append(tblProp);

        //    // 添加表头. 其实有TableHeader对象的
        //    TableRow headerRow = new TableRow();
        //    foreach (string headerStr in headerArray)
        //    {
        //        TableCell cell = new TableCell();
        //        cell.Append(new Paragraph(new Run(new Text(headerStr))));
        //        headerRow.Append(cell);
        //    }
        //    table.Append(headerRow);

        //    // 添加数据
        //    foreach (string[] rowArray in lstData)
        //    {
        //        TableRow row = new TableRow();
        //        foreach (string strCell in rowArray)
        //        {
        //            TableCell cell = new TableCell();
        //            cell.Append(new Paragraph(new Run(new Text(strCell))));
        //            row.Append(cell);
        //        }
        //        table.Append(row);
        //    }

        //    docBody.Append(new Paragraph(new Run(table)));

        //}


        //public Table CreateTable(List<object[]> rowsData, Columns columns, OpenXmlWordUtility word2, int borderWidth = 2)
        //{
        //    //边框宽
        //    UInt32Value widthValue = new UInt32Value((uint)borderWidth);
        //    //设置表格边框
        //    TableProperties tblProp = new TableProperties(
        //        new TableBorders(
        //        new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = widthValue },
        //        new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = widthValue },
        //        new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = widthValue },
        //        new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = widthValue },
        //        new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = widthValue },
        //        new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = widthValue },

        //        )
        //    );
        //    Table table = new Table();
        //    table.Append(tblProp);
        //    //列头
        //    var columnHeaderRow = this.CreateColumnHeaderRow(new TableStyle() { RepeatHeaderRow = true }, columns, 500);
        //    table.AppendChild(columnHeaderRow);
        //    //添加数据
        //    for (int i = 0; i < rowsData.Count; i++)
        //    {
        //        TableRow row = new TableRow();
        //        TableCell cell1 = new TableCell();
        //        cell1.Append(new Paragraph(new Run(new Text(rowsData[i][0].ToString()))));
        //        row.Append(cell1);
        //        TableCell cell2 = new TableCell();
        //        string base64 = rowsData[i][1].ToString();
        //        if (base64.length > 4000)
        //        {
        //            byte[] bytes = Convert.FromBase64String(base64);
        //            MemoryStream menStream = new MemoryStream(bytes);
        //            BinaryFormatter binFormatter = new BinaryFormatter();
        //            var picture = word2.CreatePicture(FileBaseUtility.GetBinaryDataStream(base64), "Png");
        //            cell2.Append(new Paragraph(new Run(picture)));
        //        }
        //        else
        //        {
        //            cell2.Append(new Paragraph(new Run(new Text(rowsData[i][1].ToString()))));
        //        }
        //        row.Append(cell2);
        //        table.Append(row);
        //    }
        //    return table;
        //}
    }
}
